/*
 * @Author: i@douxuefeng.cn
 * @Date: 2024-01-13 13:45:23
 * @LastEditTime: 2024-01-13 16:08:59
 * @LastEditors: i@douxuefeng.cn
 * @Description:
 */
package getIp

import (
	"encoding/json"
	"fmt"

	"gitee.com/douxuefeng/go-utils/request"
	accessToken "gitee.com/douxuefeng/go-utils/wechat/corp/access_token"
	"gitee.com/douxuefeng/go-utils/wechat/corp/config"
	"gitee.com/douxuefeng/go-utils/wechat/corp/params"
)

const (
	getApiDomainIpUrl string = params.CorpApi + "/get_api_domain_ip?access_token=%s"
	getCallBackIpUrl  string = params.CorpApi + "/getcallbackip?access_token=%s"
)

type getIp struct {
	cf *config.CorpConfig
}

func NewGetIp(cf *config.CorpConfig) *getIp {
	return &getIp{cf: cf}
}

func (a *getIp) GetApiDomainIp() *params.GetIpReply {
	token, err := accessToken.NewAccessToken(a.cf).GetAccessToken()
	if err != nil {
		return &params.GetIpReply{Errcode: 1, Errmsg: err.Error()}
	}
	req := request.NewRequest()
	resp, err := req.Get(fmt.Sprintf(getApiDomainIpUrl, token))
	if err != nil {
		return &params.GetIpReply{Errcode: 1, Errmsg: err.Error()}
	}
	var rs params.GetIpReply
	err = json.Unmarshal(resp.Body(), &rs)
	if err != nil {
		return &params.GetIpReply{Errcode: 1, Errmsg: err.Error()}
	}
	return &rs
}

func (a *getIp) GetCallBackIp() *params.GetIpReply {
	token, err := accessToken.NewAccessToken(a.cf).GetAccessToken()
	if err != nil {
		return &params.GetIpReply{Errcode: 1, Errmsg: err.Error()}
	}
	req := request.NewRequest()
	resp, err := req.Get(fmt.Sprintf(getCallBackIpUrl, token))
	if err != nil {
		return &params.GetIpReply{Errcode: 1, Errmsg: err.Error()}
	}
	var rs params.GetIpReply
	err = json.Unmarshal(resp.Body(), &rs)
	if err != nil {
		return &params.GetIpReply{Errcode: 1, Errmsg: err.Error()}
	}
	return &rs
}
